<!-- src/components/class-center/NoticeEditForm.vue -->
<template>
  <div class="notice-edit-form">
    <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        label-position="top"
    >
      <!-- 通知标题 -->
      <el-form-item label="通知标题" prop="title">
        <el-input
            v-model="formData.title"
            placeholder="请输入通知标题"
            maxlength="200"
            show-word-limit
        />
      </el-form-item>

      <!-- 通知类型 -->
      <el-form-item label="通知类型" prop="typeId">
        <el-select
            v-model="formData.typeId"
            placeholder="请选择通知类型"
            style="width: 100%"
        >
          <el-option
              v-for="type in noticeTypes"
              :key="type.typeId"
              :label="type.typeName"
              :value="type.typeId"
          >
            <span style="float: left">{{ type.typeName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">
              {{ type.description }}
            </span>
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 接收对象 -->
      <el-form-item label="接收对象" prop="recipients">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-checkbox-group v-model="formData.recipientTypes">
              <el-checkbox label="class">按班级</el-checkbox>
              <el-checkbox label="user">按个人</el-checkbox>
              <el-checkbox label="role">按角色</el-checkbox>
            </el-checkbox-group>
          </el-col>
          <el-col :span="16">
            <!-- 班级选择 -->
            <div v-if="formData.recipientTypes.includes('class')" class="recipient-section">
              <el-select
                  v-model="formData.selectedClasses"
                  multiple
                  placeholder="请选择班级"
                  style="width: 100%; margin-bottom: 10px;"
                  @change="handleRecipientChange"
              >
                <el-option
                    v-for="classItem in classOptions"
                    :key="classItem.classId"
                    :label="classItem.displayName"
                    :value="classItem.classId"
                />
              </el-select>
            </div>

            <!-- 个人选择 -->
            <div v-if="formData.recipientTypes.includes('user')" class="recipient-section">
              <el-select
                  v-model="formData.selectedUsers"
                  multiple
                  filterable
                  placeholder="请选择用户"
                  style="width: 100%; margin-bottom: 10px;"
                  @change="handleRecipientChange"
              >
                <el-option
                    v-for="user in userOptions"
                    :key="user.id"
                    :label="`${user.name} (${user.username})`"
                    :value="user.id"
                />
              </el-select>
            </div>

            <!-- 角色选择 -->
            <div v-if="formData.recipientTypes.includes('role')" class="recipient-section">
              <el-select
                  v-model="formData.selectedRoles"
                  multiple
                  placeholder="请选择角色"
                  style="width: 100%; margin-bottom: 10px;"
                  @change="handleRecipientChange"
              >
                <el-option label="学生" value="student" />
                <el-option label="教师" value="teacher" />
                <el-option label="管理员" value="admin" />
              </el-select>
            </div>
          </el-col>
        </el-row>

        <!-- 接收对象预览 -->
        <div v-if="recipientPreview.length > 0" class="recipient-preview">
          <el-tag
              v-for="recipient in recipientPreview"
              :key="recipient.id"
              closable
              @close="removeRecipient(recipient)"
              style="margin: 2px;"
          >
            {{ recipient.name }}
          </el-tag>
        </div>
        <div v-else class="recipient-empty">
          <span style="color: #909399; font-size: 12px;">请选择接收对象</span>
        </div>
      </el-form-item>

      <!-- 通知描述 -->
      <el-form-item label="通知描述">
        <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入通知描述（可选）"
            maxlength="500"
            show-word-limit
        />
      </el-form-item>

      <!-- 通知正文 -->
      <el-form-item label="通知正文" prop="content">
        <el-input
            v-model="formData.content"
            type="textarea"
            :rows="8"
            placeholder="请输入通知正文内容"
            maxlength="2000"
            show-word-limit
        />
      </el-form-item>

      <!-- 关联课程（可选） -->
      <el-form-item label="关联课程">
        <el-select
            v-model="formData.scheduleId"
            placeholder="选择关联课程（可选）"
            style="width: 100%"
            clearable
            filterable
        >
          <el-option
              v-for="schedule in scheduleOptions"
              :key="schedule.scheduleId"
              :label="schedule.displayName"
              :value="schedule.scheduleId"
          />
        </el-select>
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <div class="form-actions">
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            {{ isEditing ? '更新通知' : '发布通知' }}
          </el-button>
          <el-button @click="handleCancel">取消</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { createNotice, updateNotice, fetchNoticeTypes, fetchClassOptions, fetchUserOptions, fetchScheduleOptions } from '@/api/teacher'

// Props
interface Props {
  noticeData?: any
  isEditing: boolean
}

const props = defineProps<Props>()
const emit = defineEmits(['success', 'cancel'])

// 响应式数据
const formRef = ref<FormInstance>()
const submitting = ref(false)
const loadingOptions = ref(false)

const formData = reactive({
  title: '',
  typeId: null as number | null,
  description: '',
  content: '',
  scheduleId: null as number | null,
  recipientTypes: [] as string[],
  selectedClasses: [] as number[],
  selectedUsers: [] as number[],
  selectedRoles: [] as string[]
})

const noticeTypes = ref<any[]>([])
const classOptions = ref<any[]>([])
const userOptions = ref<any[]>([])
const scheduleOptions = ref<any[]>([])

// 表单验证规则
const formRules: FormRules = {
  title: [
    { required: true, message: '请输入通知标题', trigger: 'blur' },
    { min: 2, max: 200, message: '标题长度在 2 到 200 个字符', trigger: 'blur' }
  ],
  typeId: [
    { required: true, message: '请选择通知类型', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入通知内容', trigger: 'blur' },
    { min: 10, message: '内容至少 10 个字符', trigger: 'blur' }
  ]
}

// 计算属性
const recipientPreview = computed(() => {
  const preview = [] as Array<{id: string, name: string}>

  // 班级预览
  formData.selectedClasses.forEach(classId => {
    const classItem = classOptions.value.find(c => c.classId === classId)
    if (classItem) {
      preview.push({ id: `class_${classId}`, name: `${classItem.className}(全班)` })
    }
  })

  // 用户预览
  formData.selectedUsers.forEach(userId => {
    const user = userOptions.value.find(u => u.id === userId)
    if (user) {
      preview.push({ id: `user_${userId}`, name: user.name })
    }
  })

  // 角色预览
  formData.selectedRoles.forEach(role => {
    preview.push({ id: `role_${role}`, name: `${role}(全部)` })
  })

  return preview
})

// 方法
const removeRecipient = (recipient: {id: string, name: string}) => {
  const [type, id] = recipient.id.split('_')
  switch (type) {
    case 'class':
      formData.selectedClasses = formData.selectedClasses.filter(c => c !== Number(id))
      break
    case 'user':
      formData.selectedUsers = formData.selectedUsers.filter(u => u !== Number(id))
      break
    case 'role':
      formData.selectedRoles = formData.selectedRoles.filter(r => r !== id)
      break
  }
}

const handleRecipientChange = () => {
  // 触发表单验证
  if (formRef.value) {
    formRef.value.validateField('recipients')
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    submitting.value = true

    // 从localStorage获取用户ID
    const userInfoStr = localStorage.getItem('userInfo')
    let userId = ''

    if (userInfoStr) {
      try {
        const userInfo = JSON.parse(userInfoStr)
        userId = userInfo.id || ''
      } catch (error) {
        console.error('解析用户信息失败', error)
      }
    }

    if (!userId) {
      ElMessage.error('无法获取用户信息，请重新登录')
      submitting.value = false
      return
    }

    // 构建提交数据
    const submitData = {
      title: formData.title,
      typeId: formData.typeId,
      description: formData.description,
      content: formData.content,
      scheduleId: formData.scheduleId,
      recipients: {
        classes: formData.selectedClasses,
        users: formData.selectedUsers,
        roles: formData.selectedRoles
      }
    }

    // 调用API
    let response
    if (props.isEditing && props.noticeData) {
      response = await updateNotice(props.noticeData.noticeId, submitData, parseInt(userId))
    } else {
      response = await createNotice(submitData, parseInt(userId))
    }

    if (response.success) {
      ElMessage.success(props.isEditing ? '通知更新成功' : '通知发布成功')
      emit('success', response.data)
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    submitting.value = false
  }
}

const handleCancel = () => {
  emit('cancel')
}

// 加载选项数据
const loadOptions = async () => {
  loadingOptions.value = true
  try {
    const [typesRes, classesRes, usersRes, schedulesRes] = await Promise.all([
      fetchNoticeTypes(),
      fetchClassOptions(),
      fetchUserOptions(),
      fetchScheduleOptions()
    ])

    if (typesRes.success) noticeTypes.value = typesRes.data || []
    if (classesRes.success) classOptions.value = classesRes.data || []
    if (usersRes.success) userOptions.value = usersRes.data || []
    if (schedulesRes.success) scheduleOptions.value = schedulesRes.data || []

  } catch (error) {
    console.error('加载选项数据失败:', error)
    ElMessage.error('加载选项数据失败')

    // 使用默认数据作为备用
    noticeTypes.value = [
      { typeId: 1, typeName: '课程通知', description: '课程相关通知' },
      { typeId: 2, typeName: '考试通知', description: '考试相关通知' },
      { typeId: 3, typeName: '活动通知', description: '活动相关通知' },
      { typeId: 4, typeName: '系统通知', description: '系统相关通知' }
    ]

    classOptions.value = [
      { classId: 1, className: '一年级一班' },
      { classId: 2, className: '一年级二班' }
    ]

    userOptions.value = [
      { id: 101, name: '张三', username: 'student_1001' },
      { id: 102, name: '李四', username: 'student_1002' }
    ]

    scheduleOptions.value = [
      { scheduleId: 1, displayName: '一年级一班-数学-周一第1节' },
      { scheduleId: 2, displayName: '一年级一班-语文-周二第2节' }
    ]
  } finally {
    loadingOptions.value = false
  }
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    title: '',
    typeId: null,
    description: '',
    content: '',
    scheduleId: null,
    recipientTypes: [],
    selectedClasses: [],
    selectedUsers: [],
    selectedRoles: []
  })
}

const initFormData = () => {
  if (props.isEditing && props.noticeData) {
    // 编辑模式下初始化表单数据
    Object.assign(formData, {
      title: props.noticeData.title,
      typeId: props.noticeData.typeId,
      description: props.noticeData.description,
      content: props.noticeData.content,
      scheduleId: props.noticeData.scheduleId
      // 注意：接收对象需要根据实际数据初始化，这里简化处理
    })
  } else {
    resetForm()
  }
}

// 监听
watch(() => props.isEditing, initFormData, { immediate: true })

// 添加接收对象的验证规则
watch(() => formData.recipientTypes, () => {
  // 动态添加/移除接收对象验证
  if (formRef.value) {
    formRef.value.clearValidate('recipients')
  }
})

// 生命周期
onMounted(() => {
  loadOptions()
  initFormData()
})
</script>

<style scoped>
.notice-edit-form {
  padding: 0;
}

.recipient-section {
  margin-bottom: 10px;
}

.recipient-preview {
  margin-top: 10px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
  min-height: 40px;
  border: 1px dashed #dcdfe6;
}

.recipient-empty {
  margin-top: 10px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
  min-height: 40px;
  border: 1px dashed #dcdfe6;
  display: flex;
  align-items: center;
  justify-content: center;
}

.form-actions {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

:deep(.el-form-item__label) {
  font-weight: 600;
  color: #303133;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
</style>
